package com.zs.lib_base.http

import android.content.Context
import android.text.TextUtils
import com.zs.lib_base.ext.e
import com.zs.lib_base.utils.SPHelpers
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.nio.charset.Charset
import java.util.concurrent.TimeUnit

class RetrofitHelper(context: Context) {
    var mContext:Context = context
    init {
        init()
    }

    companion object {
        fun getInstance(context: Context): RetrofitHelper {
            val instance = RetrofitHelper(context)
            return instance
        }
    }

    var client: OkHttpClient? = null
//    var authorization = "Bearer" + SPHelpers(context).getAuthorization()
    var token = SPHelpers(context).getToken()

    var mRetrofit: Retrofit? = null

    fun init() {
//        var authenticator = Authenticator { route, response ->
//            //当服务器返回的状态码为401时，会自动执行里面的代码，也就实现了自动刷新token
//            response.request().newBuilder()
//                    .addHeader("token", token)
//                    .build()
//        }
        val tokenInterceptor = Interceptor { chain ->
            //全局拦截器，往请求头部添加 token 字段，实现了全局添加 token
            val originalRequest = chain.request()//获取请求
            val tokenRequest: Request?
//            L.getInstance().d("设备号：" + device)
            if (TextUtils.isEmpty(token)) {//对 token 进行判空，如果为空，则不进行修改
                tokenRequest = originalRequest.newBuilder()//往请求头中添加 token 字段
//                    .header("Authorization", authorization)
                        .build()
                return@Interceptor chain.proceed(tokenRequest!!)
            }
            tokenRequest = originalRequest.newBuilder()//往请求头中添加 token 字段
                .header("token", token)
                    .build()
            chain.proceed(tokenRequest!!)
        }
        val noLoginInterceptor = Interceptor { chain ->
            //全局拦截器，往请求头部添加 token 字段，实现了全局添加 token
            val response = chain.proceed(chain.request())
            val responseBody = response.body()
            val source = responseBody!!.source()
            //
            source.request(java.lang.Long.MAX_VALUE) // Buffer the entire body.
            val buffer = source.buffer()
            var charset: Charset? = Charset.forName("UTF-8")
            val contentType = responseBody.contentType()
            if (contentType != null) {
                charset = contentType.charset(charset)
            }
            val bodyString = buffer.clone().readString(charset!!)
//            val baseBean = Gson().fromJson(bodyString, BaseData::class.java)
//            if (baseBean.code.equals("401") || baseBean.code.equals("1001") || baseBean.code.equals( "1002" ) ) {
//                EventBus.getDefault().post("login")
//            }
            "接口返回数据==> $bodyString".e()

//            val jsonObject = JSONObject(bodyString)
////            if (jsonObject.get("code") == "401" || (jsonObject.get("message") != null && jsonObject.get("message").toString().indexOf("登录") != -1)) {
//            if(bodyString.contains("code")){
//                if (jsonObject.get("code").toString() == "401" || jsonObject.get("code").toString() == "403") {
////                    L.getInstance().d("未登录：")
//                    EventBus.getDefault().post("noLogin")
//                }
//            }
            response
        }

        val logInterceptor = HttpLoggingInterceptor()
        logInterceptor.level = HttpLoggingInterceptor.Level.BODY
        client = OkHttpClient.Builder()
                .connectTimeout(3000, TimeUnit.SECONDS)
                .readTimeout(3000, TimeUnit.SECONDS)
                .retryOnConnectionFailure(false) //失败重连
                .addInterceptor(logInterceptor)
                .addInterceptor(noLoginInterceptor)
                .addNetworkInterceptor(tokenInterceptor)
//            .authenticator(authenticator)
                .build()
//        resetApp()
    }

//    private fun resetApp() {
//        mRetrofit = Retrofit.Builder()
//                .baseUrl(Constants.BASE_URL)//请求地址
//                .client(client)
////                .addConverterFactory(NullOrEmptyConvertFactory())
//                .addConverterFactory(GsonConverterFactory.create(GsonBuilder().serializeNulls().create()))
//
////                 .addConverterFactory(ScalarsConverterFactory.create())
//                .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
//                .build()
//    }
    fun getGsonServer(baseUrl:String): RetrofitService {
        mRetrofit = Retrofit.Builder()
                .baseUrl(baseUrl)//请求地址
                .client(client!!)
//                .addConverterFactory(NullOrEmptyConvertFactory())

                .addConverterFactory(GsonConverterFactory.create())
//            .addConverterFactory(GsonConverterFactory.create(GsonBuilder().serializeNulls().create()))
//                 .addConverterFactory(ScalarsConverterFactory.create())
                .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
                .build()
        return mRetrofit!!.create(RetrofitService::class.java)//创建RetrofitService 实体类
    }
    fun getScalarsServer(baseUrl:String): RetrofitService {
        mRetrofit = Retrofit.Builder()
            .baseUrl(baseUrl)//请求地址
            .client(client!!)
//                .addConverterFactory(NullOrEmptyConvertFactory())
            .addConverterFactory(GsonConverterFactory.create())

//                 .addConverterFactory(ScalarsConverterFactory.create())
            .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
            .build()
        return mRetrofit!!.create(RetrofitService::class.java)//创建RetrofitService 实体类
    }
//    open fun getServer(): RetrofitService {
//        return mRetrofit!!.create(RetrofitService::class.java)//创建RetrofitService 实体类
//    }


}